package org.Image.management.SpringDataService.Service.StorageIo.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.Image.management.SpringDataService.CopyUtils.CopyFileUtils;
import org.Image.management.SpringDataService.Pojo.AppConfig;
import org.Image.management.SpringDataService.Pojo.Exception.BusinessException;
import org.Image.management.SpringDataService.Pojo.Exception.StatusCode;
import org.Image.management.SpringDataService.Service.StorageIo.Pojo.Mapper.FileStorage;
import org.Image.management.SpringDataService.Service.StorageIo.Pojo.Vo.FileLimitVo;
import org.Image.management.SpringDataService.Service.StorageIo.Pojo.Vo.UploadFileVo;
import org.Image.management.SpringDataService.Service.StorageIo.mapper.FileMapper;
import org.Image.management.SpringDataService.Service.StorageIo.service.impl.FileServiceInterface;
import org.Image.management.utils.GetLocalDateTimeUtils;
import org.Image.management.utils.JsonFileUtils;
import org.springframework.stereotype.Service;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
@RequiredArgsConstructor
public class FileService extends ServiceImpl<FileMapper, FileStorage> implements FileServiceInterface {
    private final FileMapper fileMapper;
    private final AppConfig appConfig;
    private final CopyFileUtils cpyFileUtils;

    @Override
    public UploadFileVo uploadFile(File file, Long id, String description) {
        FileStorage fileStorage = getFileStorage(file, id, description);

        if (fileMapper.insert(fileStorage) <= 0) {
            throw new BusinessException(StatusCode.ERROR_CODE, "文件上传失败");
        }

        // 保存文件到上传目录
        try {
            Files.copy(file.toPath(), Path.of(fileStorage.getPath()));
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(StatusCode.ERROR_CODE, "文件上传失败: " + e.getMessage());
        }

        //返回数据
        return cpyFileUtils.FileStorageToUploadFileVo(fileStorage);
    }

    private FileStorage getFileStorage(File file, Long id, String description) {
        // 获取当前时间 2025-3-27
        String uploadFormat = GetLocalDateTimeUtils.GetLocalDateTimeToString();

        // 获取上传目录 + 加上时间
        System.out.println(uploadFormat);
        Path uploadPath = Path.of(new File(appConfig.getUploadPath() + "/" + uploadFormat).getAbsolutePath());
        //获取原始文件名 - 1.jpg  123.0.0.jpg
        String originalFilename = file.getName();

        //构造唯一的文件名 (不能重复) - uuid(通用唯一识别码) de49685b-61c0-4b11-80fa-c71e95924018
        //时间(当前时间) + uuid(通用唯一识别码)=组合成新的文件名 2025-3-27:de49685b-61c0-4b11-80fa-c71e95924018
        UUID uuid = UUID.randomUUID();
        //  构造唯一的文件名
        //  String newFileName = uuid + "_" + originalFilename;
        String newFileName = uploadFormat + "-" + uuid;
        // 创建目录
        if (!Files.exists(uploadPath)) {
            try {
                Files.createDirectory(uploadPath);
                System.out.println("目录创建成功");
            } catch (Exception e) {
                System.err.println("创建目录失败: " + e.getMessage());
            }
        }

        // 保存文件到上传目录
        Path filePath = uploadPath.resolve(newFileName);
//        log.info("文件上传位置 {}", filePath);

        //添加到数据库
        //        log.info("数据封装： {}", fileStorage);
        return FileStorage.builder().uuid(newFileName)
                .userId(id)
                .description(description)
                .name(originalFilename)
                .type(new MimetypesFileTypeMap().getContentType(originalFilename))
                .path(filePath.toString())
                .build();
    }


    @Override
    public List<FileStorage> selectByUserId(Long userId) {
        //查询是否有数据
        LambdaQueryWrapper<FileStorage> last = new LambdaQueryWrapper<>(FileStorage.class).eq(FileStorage::getUserId, userId);
        return fileMapper.selectList(last);
    }

    @Override
    public List<FileStorage> selectByInquireString(Long userId, String inquireString) {
        // 查询是否有数据
        // 创建 LambdaQueryWrapper 对象
        LambdaQueryWrapper<FileStorage> queryWrapper = new LambdaQueryWrapper<>(FileStorage.class);
        // 添加查询条件
        queryWrapper.eq(FileStorage::getUserId, userId)  // 用户ID等于指定值
                .and(wrapper -> wrapper
                        .like(FileStorage::getDescription, inquireString)// 文件备注包含指定内容(模糊查询)
                        .or()
                        .like(FileStorage::getName, inquireString) // 文件名包含指定内容(模糊查询)
                )
                .orderByDesc(FileStorage::getCreatedAt); // 按创建时间降序排列
        return fileMapper.selectList(queryWrapper);
    }

    @Override
    public FileStorage selectByFileId(Long userId,String fileId) {
        // 查询 文件信息
        LambdaQueryWrapper<FileStorage> queryWrapper = new LambdaQueryWrapper<>(FileStorage.class).allEq(
                Map.of(
                        FileStorage::getUserId , userId,
                        FileStorage::getUuid, fileId
                )
        );
        return fileMapper.selectOne(queryWrapper);
    }


    @Override
    public boolean updateFile(FileStorage fileService) {
//        log.info("更新文件： {}", fileService);
        int update = fileMapper.update(fileService, new LambdaQueryWrapper<FileStorage>().eq(FileStorage::getUuid, fileService.getUuid()));

        return update > 0;
    }

    @Override
    public FileLimitVo InquireFile(int Current, int limit) {
        return null;
    }

    @Override
    public boolean deleteFile(String fileId, Long userId) {
        LambdaQueryWrapper<FileStorage> last = new LambdaQueryWrapper<FileStorage>().allEq(Map.of(FileStorage::getUuid, fileId, FileStorage::getUserId, userId));

        FileStorage fileStorage = fileMapper.selectOne(last);

        if (fileStorage.getPath() != null) {
            JsonFileUtils.saveJsonToFile("deleteFile", fileStorage);
        }

        return fileMapper.delete(last) > 0;
    }

    @Override
    public void reviseImage(Long userId,String uuid, File customData) {
        FileStorage localFileStorage = selectByFileId(userId, uuid);

        JsonFileUtils.saveJsonToFile("deleteFile", localFileStorage);

        FileStorage fileStorage = getFileStorage(customData, userId, null);

        fileStorage.setUuid(uuid);

        updateFile(fileStorage);
        // 保存文件到上传目录
        try {
            Files.copy(customData.toPath(), Path.of(fileStorage.getPath()));
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(StatusCode.ERROR_CODE, "文件上传失败: " + e.getMessage());
        }

    }
}
